﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Text;
using RAP.Framework.Libary.DataSource.Model;
using RAP.Framework.Libary.Utils;
using RAP.Framework.Libary.Utils.Grouped;

namespace RAP.Framework.Libary.DataSource.DataReader
{
  /// <summary>
  /// 键值对解析器
  /// </summary>
  public class DictionaryParser : DataReaderParser
  {
    /// <summary>
    /// 将DataReader当前结果集转换成键值对集合
    /// </summary>
    /// <param name="dataReader"></param>
    /// <param name="pickFields"></param>
    /// <param name="type">结果类型名称</param>
    /// <param name="parseContext">解析时用到的上下文对象</param>
    /// <returns></returns>
    public override ParseResult ParseData(IDataReader dataReader, IList pickFields, string type, DataParseContext parseContext)
    {
      var list = new ArrayList();
      var fields = this.GetFields(dataReader, pickFields);
      var onlyGetFirstData = pickFields.IsNotNullOrEmpty();
      while (dataReader.Read())
      {
        var data = CreateDataModel() as IDictionary;
        for (var i = 0; i < fields.Count; i++)
        {
          var field = fields[i];
          data.Add(field.Name, GetDBValue(dataReader, field));
        }
        if (onlyGetFirstData)
        {
          return new ParseResult
          {
            DataValue = data,
            DataCount = 1
          };
        }
        list.Add(data);
      }
      return new ParseResult
      {
        DataValue = parseContext.ModelParams.IsNullOrEmpty() ? (object)list : list.ToGroupedDictionary(parseContext.ModelParams),
        DataCount = list.Count
      };
    }
  }
}
